package com.mhl.campuscabinet;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.mhl.adapter.ProductAdapter;
import com.mhl.entity.Product;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RecmActivity extends AppCompatActivity {

    private List<Product> productList = new ArrayList<>();
    private SmartRefreshLayout refreshLayout;
    private ProductAdapter adapter;
    TextView search;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recm);

//        Intent intent	= getIntent();
//        //获取这个Intent对象的Extra中对应键的值
//        String string 	= intent.getExtras().getString("result");
//        search.setText(string);

        initProducts();
        RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycle_view);
        StaggeredGridLayoutManager layoutManager = new
                StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        // 解决重新分配高度的问题
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull @NotNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                layoutManager.invalidateSpanAssignments(); //防止第一行到顶部有空白区域
            }
        });
        adapter = new ProductAdapter(productList, this);
        recyclerView.setAdapter(adapter);
        refreshLayout = (SmartRefreshLayout)findViewById(R.id.smart_refresh);
        // 修改阻尼效果（0 - 1），越小阻尼越大，默认0.5
        refreshLayout.setDragRate(0.6f);
        // 设置主题颜色
        refreshLayout.setPrimaryColorsId(R.color.purple_200);
        // 设置 Header 为 贝塞尔雷达 样式
        refreshLayout.setRefreshHeader(new BezierRadarHeader(this).setEnableHorizontalDrag(true));
        // 设置 Footer 为 球脉冲 样式
        refreshLayout.setRefreshFooter(new BallPulseFooter(this).setSpinnerStyle(SpinnerStyle.Scale));
        // 下拉刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                refreshProduct();
            }
        });
        // 上拉加载
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                loadMoreProduct();
            }
        });

        search = findViewById(R.id.search);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RecmActivity.this,ListActivity.class);
                startActivityForResult(intent,1);
            }
        });
    }

    // 初始化首页推荐商品列表，再onCreate以及下拉刷新中调用
    private void initProducts() {
        productList.clear(); // 这句话保留在第一行，用于清空list用的
        loadProducts();
    }

    // 这里客户端需要修改
    // 推荐直接改这个函数
    // 用于向服务器发送获取新内容的请求
    // 服务器应该发送一个json数组，包含每个产品对象的name，图片url（七牛云服务器中的图片地址）以及
    // 产品的价格
    // 客户端在接收json后需要将每个对象组装成一个个的Product对象存放到productList中即可
    private void loadProducts() {
        // 这里涉及网络
        // 建议客户端二人看一下9.2的OkHttp
        // 研究一下回调函数
        // 解析json的也麻烦看一下吧，推荐使用GSON
    }

    // 前端测试用的函数，没什么卵用
    private String getRandomLengthName(String name) {
        Random random = new Random();
        int length = random.nextInt(20) + 1;
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < length; i++) {
            builder.append(name);
        }
        return builder.toString();
    }

    // 下拉刷新后调用，负责建立子线程以及更改UI
    private void refreshProduct() {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                initProducts();
                adapter.notifyDataSetChanged();
                refreshLayout.finishRefresh(true);
            }
        });
    }

    // 上拉加载后调用，负责建立子线程以及更改UI
    private void loadMoreProduct() {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                loadProducts();
                adapter.notifyDataSetChanged();
                refreshLayout.finishLoadMore(true);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String result = data.getExtras().getString("result");//得到新Activity 关闭后返回的数据
        Log.d("TAG", "onActivityResult: "+result);
        search.setText(result);
    }


}